package com.pingao.mp.modular.sys.controller;

import com.pingao.mp.modular.sys.service.UserRolesService;
import com.pingao.mp.modular.sys.service.UserService;
import com.pingao.mp.utils.Constant;
import com.pingao.mp.utils.set.MapBuilder;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping(value = "/sys/userRoles")
public class UserRolesController {

    @Autowired
    private UserRolesService userRolesService;
    @Autowired
    private UserService userService;

    @GetMapping(value = "/edit/{userId}")
    @RequiresPermissions(value = "sys.userRoles.edit")
    public String userRolesEdit(@PathVariable("userId") Integer userId, ModelMap modelMap) {
        modelMap.addAttribute("user", userService.getUserByIdForRoles(userId));
        return "sys/user/user_role";
    }

    @GetMapping(value = "/list/{userId}")
    @RequiresPermissions("sys.userRoles.edit")
    @ResponseBody
    public Object list(@PathVariable("userId") Integer userId) {
        return userRolesService.listByUserId(userId);
    }

    @PostMapping(value = "/edit/{userId}")
    @RequiresPermissions("sys.userRoles.edit")
    @ResponseBody
    public Object UserRolesEdit(
            @PathVariable("userId") Integer userId,
            @RequestParam(value = "roleIds[]", required = false) List<Integer> roleIds
    ) {
        MapBuilder<String, Object> m = new MapBuilder<>();
        try {
            userRolesService.saveUserRoles(userId, roleIds);
            m.put(Constant.ApiStatus, true).put(Constant.ApiMsg, "修改成功");
        } catch (Exception e) {
            m.put(Constant.ApiStatus, false).put(Constant.ApiMsg, e.getMessage());
        }
        return m.get();
    }
}
